//
//  LoginSettingVC.m
//  SSWiFi
//
//  Created by 酷安 @啥也不会啊啊啊啊啊啊  on 2024/3/10.
//

#import "LoginSettingVC.h"
#import "Api.h"

@interface LoginSettingVC ()<UITableViewDelegate,UITableViewDataSource>
@property (strong,nonatomic) NSMutableArray *datasource;
@end

@implementation LoginSettingVC
static NSString * const cell_identifier = @"LoginSettingVC_cell_identifier";
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"登录设置";
    self.tableView.delegate = self;
    self.tableView.dataSource= self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cell_identifier];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem qmui_itemWithTitle:@"新增" target:self action:@selector(addClick)];
    [self testLogin];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [UserConfig loadLoginIps];
}

- (void)addClick{
    QMUIDialogTextFieldViewController *dialogViewController = [[QMUIDialogTextFieldViewController alloc] init];
    dialogViewController.title = @"新增登录ip";
    [dialogViewController addTextFieldWithTitle:@"IP地址" configurationHandler:^(QMUILabel *titleLabel, QMUITextField *textField, CALayer *separatorLayer) {
        textField.placeholder = @"请输入ip地址:192.168.0.1";
        textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        textField.keyboardType = UIKeyboardTypeASCIICapable;
    }];
    [dialogViewController addTextFieldWithTitle:@"登录密码" configurationHandler:^(QMUILabel *titleLabel, QMUITextField *textField, CALayer *separatorLayer) {
        textField.placeholder = @"请输入登录密码";
        textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        textField.keyboardType = UIKeyboardTypeASCIICapable;
    }];
    dialogViewController.enablesSubmitButtonAutomatically = NO;// 为了演示效果与第二个 cell 的区分开，这里手动置为 NO，平时的默认值为 YES
    [dialogViewController addCancelButtonWithText:@"取消" block:nil];
    [dialogViewController addSubmitButtonWithText:@"确定" block:^(QMUIDialogTextFieldViewController *aDialogViewController) {
        NSString *ip = [aDialogViewController.textFields.firstObject.text qmui_trim];
        NSString *pwd = [aDialogViewController.textFields.lastObject.text qmui_trim];
        if (ip.length == 0 || pwd.length == 0) {
            [QMUITips showInfo:@"请填写内容" inView:aDialogViewController.view];
            return;
        }
        [aDialogViewController hide];
        [self.datasource addObject:[@{@"ip":ip,@"pwd":pwd} mutableCopy]];
        [UserConfig saveLoginIps:[self datasource]];
        [self testLogin];
    }];
    [dialogViewController show];
}

- (void)testLogin{
    for(NSDictionary *cdict in self.datasource){
        [cdict setValue:@"0" forKey:@"result"];
    }
    [self reloadData];
    [QMUITips showLoading:@"测试中.." inView:self.view];
    [Utils testLoginIp:[self datasource] loginPaths:[UserConfig serverPaths] CallBack:^(NSArray * _Nonnull successArr) {
        [QMUITips hideAllTips];
        [self fillData:successArr];
    }];
}

- (void)fillData:(NSArray *)successArr{
    for(NSDictionary *dict in successArr){
        for(NSDictionary *cdict in self.datasource){
            [cdict setValue:@"0" forKey:@"result"];
            NSString *ri_d = [dict objectForKey:@"ip"];
            NSString *ci_d = [cdict objectForKey:@"ip"];
            
            NSString *rp_d = [dict objectForKey:@"pwd"];
            NSString *cp_d = [dict objectForKey:@"pwd"];
            
            NSLog(@"ri_d: %@ -> ci_d:%@", ri_d, ci_d);
            NSLog(@"rp_d: %@ -> cp_d:%@",rp_d, cp_d);
            
            if([ri_d isEqualToString:ci_d] &&
               [rp_d isEqualToString:cp_d]
               ){
                [cdict setValue:@"1" forKey:@"result"];
            }
        }
    }
    [self reloadData];
    
}

- (void)reloadData{
    [self.tableView reloadData];
    if(self.datasource.count == 0){
        [self showEmptyViewWithText:@"暂无数据" detailText:nil buttonTitle:@"新增" buttonAction: @selector(addClick)];
        [self.emptyView setHidden:NO];
    }else{
        [self.emptyView setHidden:YES];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cell_identifier];
    if(!cell){
        cell = [tableView dequeueReusableCellWithIdentifier:cell_identifier];
    }
    NSDictionary *loginInfo = [self.datasource objectAtIndex:indexPath.row];
    cell.textLabel.text = [loginInfo valueForKey:@"ip"];
    cell.detailTextLabel.text = [loginInfo valueForKey:@"pwd"];
    NSLog(@"loginInfo: %@",loginInfo);
    if([[loginInfo valueForKey:@"result"] integerValue] == 1){
        cell.contentView.backgroundColor = [UIColor greenColor];
    }else{
        if (@available(iOS 13.0, *)) {
            cell.contentView.backgroundColor = [UIColor systemBackgroundColor];
        } else {
            cell.contentView.backgroundColor = [UIColor whiteColor];
        }
    }
   
    return cell;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
//    return self.datasource.count > 1;
    return YES;
}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath{
    MJWeakSelf;
   
    UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        [weakSelf delete:indexPath];
        completionHandler(YES);
    }];
    return [UISwipeActionsConfiguration configurationWithActions:@[delete]];
}

- (void)delete:(NSIndexPath *)indexpath{
    [self.datasource removeObjectAtIndex:indexpath.row];
    [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
    
    [UserConfig saveLoginIps:[self datasource]];
    if(self.datasource.count == 0){
        [self reloadData];
    }
}
 


- (NSMutableArray *)datasource{
    if(!_datasource){
        _datasource = [[NSMutableArray alloc] init];
        for(NSDictionary *d in [UserConfig loginIps]){
            [_datasource addObject:[d mutableCopy]];
        }
    }
    return _datasource;
}

@end
